//
//  moneyOperationView.swift
//  压岁_IOS
//
//  Created by 梓简王 on 2017/7/18.
//  Copyright © 2017年 梓简王. All rights reserved.
//

import Foundation
import QorumLogs
import TextFieldEffects
import Alamofire

protocol moneyOperationDelegate{
    func moneyOperation(moneyString:String,operationDetail:String)
}

class moneyOperationView: UIView,UITextFieldDelegate {
    var selfFrame:CGRect?
    //验证手机号码界面控件
    var moneyDetail: AkiraTextField?
    var operationMoney: AkiraTextField?
    var delegate:moneyOperationDelegate?
    var confirmBtn:UIButton?
    //手机号码确认界面控件位置
    var moneyDetailFrame:CGRect?
    var operationMoneyFrame:CGRect?
    var confirmFrame:CGRect?
    var confirmCenter:CGPoint?
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        selfFrame = frame
        initUI()
    }
    
    func initUI(){
        //初始化控件
        self.backgroundColor = UIColor.whiteColor()
        self.layer.cornerRadius = 5
        self.clipsToBounds = true
        //初始化控件位置
        moneyDetailFrame = CGRect(x: 23, y: 23, width: Int((self.selfFrame?.width)!) - 46, height: 60)
        operationMoneyFrame = CGRect(x: 23, y: 83, width: Int((self.selfFrame?.width)!) - 46, height: 60)
        //创建手机验证界面对应控件
        self.moneyDetail = AkiraTextField(frame: self.moneyDetailFrame!)
        self.moneyDetail?.borderColor = commonVariable.IRONCOLOR
        self.moneyDetail?.placeholderColor = commonVariable.IRONCOLOR
        self.moneyDetail?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.moneyDetail?.placeholder = "请输入此次操作详情"
        
        self.operationMoney = AkiraTextField(frame: operationMoneyFrame!)
        self.operationMoney?.borderColor = commonVariable.IRONCOLOR
        self.operationMoney?.placeholderColor = commonVariable.IRONCOLOR
        self.operationMoney?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.operationMoney?.placeholder = "请输入操作金额"
        
        self.moneyDetail?.delegate = self
        self.operationMoney?.delegate = self
        
        self.operationMoney?.inputView = commonVariable.NUMPAD
        
        
        self.confirmFrame = CGRect(x: 0, y: 0, width: 100, height: 35)
        self.confirmCenter = CGPoint(x: (selfFrame?.width)!/2, y: 163.0)
        //创建确认按钮
        self.confirmBtn = commonTool.initLoginBtn("确 定", rect: confirmFrame!, center: confirmCenter!)
        self.confirmBtn?.addTarget(self, action: "moneyOperation", forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(self.confirmBtn!)
        self.addSubview(moneyDetail!)
        self.addSubview(operationMoney!)
    }
    
    //验证手机与验证码
    func moneyOperation(){
        if(self.moneyDetail?.text == "" || self.operationMoney?.text == ""){
            SweetAlert().showAlert("亲", subTitle: "请填写一下具体信息嘛~", style: AlertStyle.Warning)
            return
        }
        let tempRecord = commonAccountRecord()
        if(commonVariable.LOCAL_USER?.commonRoleType == "2"){
            tempRecord.recordType = "1"
            tempRecord.operationUserID = "\((commonVariable.LOCAL_USER?.id)!)"
            tempRecord.operationUserRole = "\((commonVariable.LOCAL_USER?.commonRoleType)!)"
            tempRecord.recordRemark = "\((self.moneyDetail?.text)!)"
            tempRecord.recordCreateTime = commonTool.getUnixTime()
            tempRecord.operationMoney = self.operationMoney?.text!
            tempRecord.beforeBalance = (commonVariable.COMMONACCOUNT?.balance)!
            let operationMoney = Double((self.operationMoney?.text)!)
            let befBalance = Double(tempRecord.beforeBalance!)
            if((befBalance! - operationMoney!) < 0){
                SweetAlert().showAlert("亲", subTitle: "您账户余额不足啦!", style: AlertStyle.Warning)
                return
            }
            tempRecord.afterBalance = String(format: "%.2f", befBalance! - operationMoney!)
            tempRecord.accountID = "\((commonVariable.COMMONACCOUNT?.id)!)"
        }else{
            tempRecord.recordType = "0"
            tempRecord.operationUserID = "\((commonVariable.LOCAL_USER?.id)!)"
            tempRecord.operationUserRole = "\((commonVariable.LOCAL_USER?.commonRoleType)!)"
            tempRecord.recordRemark = "\((self.moneyDetail?.text)!)"
            tempRecord.recordCreateTime = commonTool.getUnixTime()
            tempRecord.operationMoney = self.operationMoney?.text!
            tempRecord.beforeBalance = (commonVariable.COMMONACCOUNT?.balance)!
            let operationMoney = Double((self.operationMoney?.text)!)
            let befBalance = Double(tempRecord.beforeBalance!)
            tempRecord.afterBalance = String(format: "%.2f", befBalance! + operationMoney!)
            tempRecord.accountID = "\((commonVariable.COMMONACCOUNT?.id)!)"
        }
        
        self.userInteractionEnabled = false
        commonVariable.LOADING_PACMAN.center = commonVariable.WINDOWSCENTER
        self.addSubview(commonVariable.LOADING_PACMAN)
        commonVariable.LOADING_PACMAN.startAnimation()
        
        

        let body = ["AccountType":"0","AccountRecord":"\(commonTool.dic2Json(tempRecord.toDict()))"]
        QL1(body)
        self.confirmBtn?.setTitle("正在添加...", forState: UIControlState.Normal)
        Alamofire.request(.POST, commonVariable.ACCOUNTBALANCEOPERATION,parameters:body,headers:nil).responseJSON() {
            response in
            self.confirmBtn?.setTitle("绑 定", forState: UIControlState.Normal)
            self.userInteractionEnabled = true
            commonVariable.LOADING_PACMAN.stopAnimation()
            commonVariable.LOADING_PACMAN.removeFromSuperview()
            guard let JSONDIC = response.result.value else {
                QL4(response.result.error)
                switch response.result.error!.code {
                case -1009 :
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                case 3840:
                    SweetAlert().showAlert("对不起", subTitle: "服务出现故障，请联系管理员", style: AlertStyle.Error)
                case -1001 :
                    
                    SweetAlert().showAlert("对不起", subTitle: "上传信息超时", style: AlertStyle.Error)
                default:
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                }
                return }
            QL2(JSONDIC)
            let resultDict = JSONDIC as? NSDictionary
            let jsonObj = JSON(JSONDIC)
            let errorCode = jsonObj["errorcode"].intValue
            let errorMsg = jsonObj["message"].stringValue
            QL2(errorMsg)
            if errorCode != 1 {
                SweetAlert().showAlert("对不起", subTitle: "\(errorMsg)", style: AlertStyle.Warning)
            }else{
                commonVariable.COMMONACCOUNT?.balance = tempRecord.afterBalance!
                QL1("上传成功")
                self.delegate?.moneyOperation((self.operationMoney?.text)!, operationDetail: (self.moneyDetail?.text)!)
            }
        }
    }
    //MARK: -textfield代理实现
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}